import { ModalForm, ProFormSelect, ProFormSwitch } from '@ant-design/pro-components';
import { message } from 'antd';
import { useState } from 'react';
import { getShifts, updateSchedule } from '../../service';
import { queryParkinglotNamesForSchedule } from '../../TollCollector/service';
import { ScheduleManagementTableItem, UpdateScheduleType } from '../../types.d';

const UpdateSchedule = (props: {
  currItem: ScheduleManagementTableItem;
  visible: boolean;
  reload: () => void;
  close: () => void;
}) => {
  const { currItem, reload, close, visible } = props;
  const [allPk, setAllPk] = useState<boolean>(currItem.allParkValid);
  return (
    <ModalForm<UpdateScheduleType>
      title={`${currItem.name}-${currItem.day}`}
      layout="horizontal"
      width="40vw"
      visible={visible}
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 14 }}
      modalProps={{
        destroyOnClose: true,
        onCancel: close,
        maskClosable: false,
      }}
      initialValues={{
        shiftConfigName: currItem.shiftConfigName,
        parkingLotIds: currItem?.parkingLots?.map((item) => item.parkingLotId) || [],
        allParkValid: currItem.allParkValid,
      }}
      onFinish={async (values) => {
        const data2up: UpdateScheduleType = {
          id: currItem._id,
          shiftConfigName: values.shiftConfigName,
          parkingLotIds: values.parkingLotIds,
          allParkValid: values.allParkValid,
        };
        const res = await updateSchedule(data2up);
        if (!res?.success) {
          message.error({ content: res?.message, key: 'up_schedule' });
          return false;
        }
        message.success({ content: '更新成功', key: 'up_schedule' });
        reload();
        close();
        return true;
      }}
    >
      <ProFormSelect
        name="shiftConfigName"
        label="执勤班次"
        debounceTime={300}
        showSearch
        required
        placeholder="请选择用户执勤班次"
        request={(val) => getShifts(val.keyWords, currItem.ownerId)}
      />
      <ProFormSwitch
        name="allParkValid"
        label="全部路段"
        fieldProps={{
          onChange: (v) => {
            setAllPk(v);
          },
        }}
      />
      {!allPk && (
        <ProFormSelect
          name="parkingLotIds"
          label="选择路段"
          showSearch
          mode="multiple"
          debounceTime={300}
          placeholder="请选择路段"
          rules={[
            {
              required: true,
              message: '请选择路段',
              validator: (_, val) => {
                if (!val || val.length < 1) {
                  return Promise.reject(new Error('执勤路段不可为空'));
                }
                if (val && val.length <= 20) {
                  return Promise.resolve(val);
                }
                return Promise.reject(new Error('执勤路段最多选择20个'));
              },
            },
          ]}
          request={(val) =>
            queryParkinglotNamesForSchedule(
              val.keyWords,
              currItem.ownerId,
              currItem?.parkingLots?.map((item) => ({
                label: item.parkingLotName,
                value: item.parkingLotId,
              })),
            )
          }
        />
      )}
    </ModalForm>
  );
};

export default UpdateSchedule;
